<template>
  <div class="home">
    <el-card class="welcome-card">
      <template #header>
        <div class="card-header">
          <h2>欢迎来到涂色抢地盘游戏！</h2>
        </div>
      </template>
      
      <div class="game-description">
        <p>这是一个充满策略和创意的多人涂色游戏！</p>
        <p>通过涂色占领画布区域，争夺地盘，成为最终的胜利者！</p>
        
        <!-- 游戏规则弹窗 -->
        <div class="rules-section">
          <el-popover 
            placement="bottom" 
            title="🎮 游戏规则详解" 
            :width="500" 
            trigger="hover"
            popper-class="game-rules-popover"
          >
            <template #reference>
              <el-button type="primary" plain class="rules-button">
                <el-icon><InfoFilled /></el-icon>
                游戏规则
              </el-button>
            </template>
            <div class="rules-content">
              <div class="rule-section">
                <h4>🎯 游戏目标</h4>
                <p>在有限时间内，通过涂色占领画布区域，游戏结束时占领面积最大的玩家获胜。</p>
              </div>
              
              <div class="rule-section">
                <h4>🎨 游戏玩法</h4>
                <ul>
                  <li>每位玩家选择一种独特的颜色</li>
                  <li>使用鼠标在画布上点击或拖拽进行涂色</li>
                  <li>涂色的区域会变成你的颜色，计入你的得分</li>
                  <li>可以覆盖其他玩家的颜色来扩大自己的地盘</li>
                </ul>
              </div>
              
              <div class="rule-section">
                <h4>⏰ 游戏时间</h4>
                <p>每局游戏时间可自定义设置，通常在3-10分钟之间。</p>
              </div>
              
              <div class="rule-section">
                <h4>🏆 胜利条件</h4>
                <p>游戏结束时，系统会计算每位玩家涂色的像素数量，占领面积最大的玩家获胜。</p>
              </div>
              
              <div class="rule-section">
                <h4>💡 策略提示</h4>
                <ul>
                  <li>优先占领画布中心区域</li>
                  <li>注意观察其他玩家的动向</li>
                  <li>合理分配时间，不要只专注一个区域</li>
                  <li>利用画布的边界和角落</li>
                </ul>
              </div>
            </div>
          </el-popover>
        </div>
      </div>
      
      <div class="action-buttons">
        <el-button type="primary" size="large" @click="showCreateRoomDialog = true">
          <el-icon><Plus /></el-icon>
          创建房间
        </el-button>
        
        <el-button type="success" size="large" @click="showJoinRoomDialog = true">
          <el-icon><UserFilled /></el-icon>
          加入房间
        </el-button>
      </div>
    </el-card>
    
    <!-- 创建房间对话框 -->
    <el-dialog v-model="showCreateRoomDialog" title="创建房间" width="400px">
      <el-form :model="createRoomForm" :rules="createRoomRules" ref="createRoomFormRef">
        <el-form-item label="房间名称" prop="name">
          <el-input v-model="createRoomForm.name" placeholder="请输入房间名称" />
        </el-form-item>
        
        <el-form-item label="玩家昵称" prop="playerName">
          <el-input v-model="createRoomForm.playerName" placeholder="请输入你的昵称" />
        </el-form-item>
        
        <el-form-item label="房间密码" prop="password">
          <el-input v-model="createRoomForm.password" placeholder="可选，留空为公开房间" />
        </el-form-item>
        
        <el-form-item label="最大玩家数" prop="maxPlayers">
          <el-select v-model="createRoomForm.maxPlayers" placeholder="选择最大玩家数">
            <el-option label="2人" :value="2" />
            <el-option label="3人" :value="3" />
            <el-option label="4人" :value="4" />
            <el-option label="5人" :value="5" />
            <el-option label="6人" :value="6" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateRoomDialog = false">取消</el-button>
        <el-button type="primary" @click="createRoom" :loading="creating">
          创建房间
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 加入房间对话框 -->
    <el-dialog v-model="showJoinRoomDialog" title="加入房间" width="400px">
      <el-form :model="joinRoomForm" :rules="joinRoomRules" ref="joinRoomFormRef">
        <el-form-item label="房间ID" prop="roomId">
          <el-input v-model="joinRoomForm.roomId" placeholder="请输入房间ID" />
        </el-form-item>
        
        <el-form-item label="玩家昵称" prop="playerName">
          <el-input v-model="joinRoomForm.playerName" placeholder="请输入你的昵称" />
        </el-form-item>
        
        <el-form-item label="房间密码" prop="password">
          <el-input v-model="joinRoomForm.password" placeholder="如果房间有密码，请输入" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showJoinRoomDialog = false">取消</el-button>
        <el-button type="primary" @click="joinRoom" :loading="joining">
          加入房间
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useGameStore } from '@/stores/game'
import { gameService } from '@/services/gameService'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'

const router = useRouter()
const gameStore = useGameStore()

// 对话框状态
const showCreateRoomDialog = ref(false)
const showJoinRoomDialog = ref(false)

// 加载状态
const creating = ref(false)
const joining = ref(false)

// 表单引用
const createRoomFormRef = ref()
const joinRoomFormRef = ref()

// 创建房间表单
const createRoomForm = reactive({
  name: '',
  playerName: '',
  password: '',
  maxPlayers: 6
})

// 加入房间表单
const joinRoomForm = reactive({
  roomId: '',
  playerName: '',
  password: ''
})

// 表单验证规则
const createRoomRules = {
  name: [
    { required: true, message: '请输入房间名称', trigger: 'blur' },
    { min: 2, max: 20, message: '房间名称长度在2到20个字符', trigger: 'blur' }
  ],
  playerName: [
    { required: true, message: '请输入玩家昵称', trigger: 'blur' },
    { min: 2, max: 15, message: '昵称长度在2到15个字符', trigger: 'blur' }
  ],
  maxPlayers: [
    { required: true, message: '请选择最大玩家数', trigger: 'change' }
  ]
}

const joinRoomRules = {
  roomId: [
    { required: true, message: '请输入房间ID', trigger: 'blur' }
  ],
  playerName: [
    { required: true, message: '请输入玩家昵称', trigger: 'blur' },
    { min: 2, max: 15, message: '昵称长度在2到15个字符', trigger: 'blur' }
  ]
}

// 创建房间
async function createRoom() {
  try {
    await createRoomFormRef.value.validate()
    
    creating.value = true
    const result = await gameService.createRoom(createRoomForm)
    
    // 设置游戏状态
    gameStore.setCurrentRoom({
      id: result.roomId,
      name: result.roomName
    })
    
    gameStore.setCurrentPlayer({
      id: result.playerId,
      name: createRoomForm.playerName,
      color: result.playerColor
    })
    
    ElMessage.success('房间创建成功！')
    showCreateRoomDialog.value = false
    
    // 跳转到游戏房间
    router.push(`/room/${result.roomCode}`)
  } catch (error) {
    console.error('创建房间失败:', error)
    ElMessage.error('创建房间失败，请重试')
  } finally {
    creating.value = false
  }
}

// 加入房间
async function joinRoom() {
  try {
    await joinRoomFormRef.value.validate()
    
    joining.value = true
    const result = await gameService.joinRoom({
      roomId: joinRoomForm.roomId,
      password: joinRoomForm.password,
      playerNickName: joinRoomForm.playerName,
      playerId: crypto.randomUUID() // 生成唯一的玩家ID
    })
    
    if (!result.success) {
      ElMessage.error(result.errorMessage || '加入房间失败')
      return
    }
    
    // 设置游戏状态
    gameStore.setCurrentRoom({
      id: result.roomId,
      name: result.roomName
    })
    
    gameStore.setCurrentPlayer({
      id: result.playerId,
      name: joinRoomForm.playerName,
      color: result.playerColor
    })
    
    ElMessage.success('成功加入房间！')
    showJoinRoomDialog.value = false
    
    // 跳转到游戏房间
    router.push(`/room/${result.roomId}`)
  } catch (error) {
    console.error('加入房间失败:', error)
    ElMessage.error('加入房间失败，请重试')
  } finally {
    joining.value = false
  }
}
</script>

<style scoped>
.home {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 100px);
}

.welcome-card {
  width: 600px;
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: #409EFF;
}

.game-description {
  margin: 30px 0;
  line-height: 1.8;
  font-size: 16px;
}

.game-description p {
  margin: 15px 0;
  color: #666;
}

.rules-section {
  margin: 25px 0;
}

.rules-button {
  font-size: 16px;
  padding: 12px 24px;
}

.action-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-top: 30px;
}

.action-buttons .el-button {
  min-width: 120px;
}

/* 游戏规则弹窗样式 */
:deep(.game-rules-popover) {
  max-width: 500px;
}

:deep(.game-rules-popover .el-popover__title) {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 15px;
}

.rules-content {
  text-align: left;
}

.rule-section {
  margin-bottom: 20px;
}

.rule-section h4 {
  color: #409EFF;
  margin: 0 0 8px 0;
  font-size: 16px;
}

.rule-section p {
  margin: 5px 0;
  color: #333;
  line-height: 1.6;
}

.rule-section ul {
  margin: 5px 0;
  padding-left: 20px;
}

.rule-section li {
  margin: 5px 0;
  color: #333;
  line-height: 1.6;
}
</style>
